	<template>
		<view class="chat-page">
			<!-- 顶部紫色渐变背景 -->
			<view class="top-bg">
				<view class="bg-shape bg-shape-1"></view>
				<view class="bg-shape bg-shape-2"></view>
				<view class="bg-shape bg-shape-3"></view>
			</view>

			<!-- 顶部导航栏 -->
			<view class="chat-header">
				<view class="header-left">
					<view class="back-btn" @click="goBack">
						<image class="back-icon" src="/static/icons/back.png" mode="aspectFit"></image>
					</view>
					<text class="header-title">智能咨询</text>
				</view>
				<view class="header-right">
					<view class="icon-btn" @click="showHistory">
						<image class="history-icon" src="/static/icons/chat_history.png" mode="aspectFit"></image>
					</view>
					<view class="icon-btn" @click="createNewSession">
						<image class="new-session-icon" src="/static/icons/new-chat.png" mode="aspectFit"></image>
					</view>
				</view>
			</view>

			<!-- 聊天内容区域 -->
			<scroll-view class="chat-content" scroll-y :scroll-top="scrollTop" @scroll="onScroll"
				:style="{ height: contentHeight + 'px' }">
				<!-- 欢迎消息 -->
				<view v-if="messages.length === 0" class="welcome-section">
					<view class="welcome-icon">🤖</view>
					<text class="welcome-title">智能零售助手</text>
					<text class="welcome-desc">您好！我可以为您提供商品推荐、价格咨询、
						使用建议等服务</text>
				</view>

				<!-- 消息列表 -->
				<view class="messages-container">
					<view v-for="(message, index) in messages" :key="index" :class="['message-item', message.role]">
						<!-- AI消息 -->
						<view v-if="message.role === 'assistant'" class="message-ai">
							<view class="avatar ai-avatar">
								<image class="avatar-image" src="/static/icons/ai-avatar.png" mode="aspectFit"></image>
							</view>
							<view class="message-content">
								<text class="message-text">{{ message.content }}</text>
								<text class="message-time">{{ formatTime(message.created_at) }}</text>
							</view>
						</view>

						<!-- 用户消息 -->
						<view v-else class="message-user">
							<view class="message-content">
								<!-- 图片消息 -->
								<view v-if="message.message_type === 'image'" class="image-message">
									<image class="uploaded-image" :src="message.image_url" mode="aspectFit"
										@click="previewImage(message.image_url)"></image>
								</view>
								<!-- 文本消息 -->
								<text v-else class="message-text">{{ message.content }}</text>
								<text class="message-time">{{ formatTime(message.created_at) }}</text>
							</view>
							<view class="avatar user-avatar">
								<image class="avatar-image" :src="userAvatar" mode="aspectFill" @error="onAvatarError"
									@load="onAvatarLoad">
								</image>
							</view>
						</view>
					</view>
				</view>

				<!-- 底部安全区域 -->
				<view class="bottom-space"></view>
			</scroll-view>

			<!-- 固定输入框区域 -->
			<view class="input-section-fixed" :style="{ bottom: safeAreaBottom + 'px' }">
				<view class="input-container">
					<scroll-view class="input-scroll" scroll-y :style="{ maxHeight: maxInputHeight + 'px' }">
						<textarea class="chat-input" :value="inputMessage" @input="onInput" placeholder="请输入您的问题..."
							:adjust-position="false" :show-confirm-bar="false" :maxlength="500" :auto-height="true"
							:cursor-spacing="20" @linechange="onLineChange"></textarea>
					</scroll-view>
					<view class="input-actions">
						<view class="upload-btn" @click="uploadImage">
							<image class="upload-icon" src="/static/icons/upload_image.png" mode="aspectFit"></image>
						</view>
						<button class="send-btn" :disabled="!canSend" @click="sendMessage">
							<text class="send-text">发送</text>
						</button>
					</view>
				</view>
			</view>

			<!-- 历史会话模态框 -->
			<view class="modal-mask" v-if="showHistoryModal" @click="closeHistoryModal">
				<view class="modal-content history-modal" @click.stop>
					<view class="modal-header">
						<text class="modal-title">历史会话</text>
						<text class="modal-close" @click="closeHistoryModal">×</text>
					</view>
					<view class="modal-body">
						<scroll-view class="sessions-list" scroll-y>
							<view v-if="sessions.length === 0" class="empty-sessions">
								<text class="empty-text">暂无历史会话</text>
							</view>
							<view v-else>
								<view v-for="session in sessions" :key="session.session_id" class="session-item"
									@click="selectSession(session.session_id)">
									<view class="session-info">
										<text class="session-time">{{ formatSessionTime(session.last_time) }}</text>
										<text class="session-count">{{ session.message_count }} 条消息</text>
									</view>
									<view class="session-actions">
										<button class="delete-btn"
											@click.stop="deleteSession(session.session_id)">删除</button>
									</view>
								</view>
							</view>
						</scroll-view>
					</view>
					<view class="modal-footer">
						<button class="modal-button confirm" @click="clearAllSessions">清空所有记录</button>
					</view>
				</view>
			</view>

			<!-- 全局加载弹窗 -->
			<view class="loading-popup-mask" v-if="globalLoading">
				<view class="loading-popup">
					<view class="loading-spinner"></view>
					<text class="loading-text">处理中...</text>
				</view>
			</view>
		</view>
	</template>

	<script>
		const API_BASE_URL = 'http://localhost:8000/api/v1';
		const BASE_URL = 'http://localhost:8000';

		export default {
			name: 'ChatPage',
			data() {
				return {
					inputMessage: '',
					messages: [],
					sessions: [],
					currentSessionId: null,
					loading: false,
					globalLoading: false,
					showHistoryModal: false,
					scrollTop: 0,
					token: '',
					contentHeight: 0,
					safeAreaBottom: 0,
					maxInputHeight: 60,
					inputLineCount: 1,
					userAvatar: '/static/icons/default-avatar.png',
					avatarLoadAttempts: 0,
					streamingMessage: '',
					isStreaming: false,
				};
			},
			computed: {
				canSend() {
					return this.inputMessage.trim() && !this.loading;
				}
			},
			onLoad() {
				this.hideTabBar();
				this.token = uni.getStorageSync('token');
				if (!this.token) {
					console.error('未找到token，请先登录');
					uni.redirectTo({
						url: '/pages/login/login'
					});
					return;
				}
				this.loadUserAvatar();
				this.loadSessions();
				this.createNewSession();
				this.calculateLayout();
			},
			onShow() {
				this.hideTabBar();
			},
			onHide() {
				this.showTabBar();
			},
			onUnload() {
				this.showTabBar();
			},
			onReady() {
				this.scrollToBottom();
			},
			onResize() {
				this.calculateLayout();
			},
			watch: {
				messages: {
					handler() {
						this.$nextTick(() => {
							this.scrollToBottom();
						});
					},
					deep: true
				}
			},
			methods: {
				calculateLayout() {
					const systemInfo = uni.getSystemInfoSync();
					const windowHeight = systemInfo.windowHeight;
					const safeArea = systemInfo.safeArea;

					this.safeAreaBottom = systemInfo.screenHeight - safeArea.bottom;

					const headerHeight = 120;
					const inputHeight = 200;
					const rpxRatio = systemInfo.windowWidth / 750;

					this.contentHeight = windowHeight - (headerHeight + inputHeight) * rpxRatio - this.safeAreaBottom;
				},

				async loadUserAvatar() {
					try {
						const [error, response] = await new Promise(resolve => {
							uni.request({
								url: `${API_BASE_URL}/users/avatar`,
								method: 'GET',
								header: {
									'Authorization': `Bearer ${this.token}`,
									'Content-Type': 'application/json'
								},
								success: (res) => resolve([null, res]),
								fail: (err) => resolve([err, null])
							});
						});

						if (error) throw error;

						if (response.statusCode === 200) {
							let avatarUrl = response.data.avatar_url;
							console.log('原始头像URL:', avatarUrl);

							if (avatarUrl && avatarUrl.startsWith('/')) {
								avatarUrl = BASE_URL + avatarUrl;
							}

							if (avatarUrl && avatarUrl.endsWith('.webp')) {
								console.log('检测到webp格式头像，尝试转换为png格式');
								this.userAvatar = avatarUrl;
							} else if (avatarUrl) {
								this.userAvatar = avatarUrl;
							} else {
								this.userAvatar = '/static/icons/default-avatar.png';
							}
							console.log('最终头像URL:', this.userAvatar);
						} else {
							console.warn('获取用户头像失败:', response.data.detail);
							this.userAvatar = '/static/icons/default-avatar.png';
						}
					} catch (error) {
						console.error('加载用户头像失败:', error);
						this.userAvatar = '/static/icons/default-avatar.png';
					}
				},

				onAvatarLoad() {
					console.log('头像加载成功');
					this.avatarLoadAttempts = 0;
				},

				onAvatarError(e) {
					console.log('头像加载失败，错误信息:', e);
					this.avatarLoadAttempts++;

					if (this.userAvatar.endsWith('.webp')) {
						console.log('webp格式头像加载失败，使用默认头像');
						this.userAvatar = '/static/icons/default-avatar.png';
						this.$forceUpdate();
						return;
					}

					if (this.avatarLoadAttempts >= 1) {
						console.log('头像加载多次失败，使用默认头像');
						this.userAvatar = '/static/icons/default-avatar.png';
						this.$forceUpdate();
					}
				},

				hideTabBar() {
					// #ifdef APP-PLUS
					uni.hideTabBar({
						animation: false
					});
					// #endif
					// #ifdef MP-WEIXIN
					wx.hideTabBar && wx.hideTabBar();
					// #endif
					// #ifdef H5
					this.hideTabBarInH5();
					// #endif
				},

				showTabBar() {
					// #ifdef APP-PLUS
					uni.showTabBar({
						animation: false
					});
					// #endif
					// #ifdef MP-WEIXIN
					wx.showTabBar && wx.showTabBar();
					// #endif
					// #ifdef H5
					this.showTabBarInH5();
					// #endif
				},

				hideTabBarInH5() {
					const tabBar = document.querySelector('.uni-tabbar');
					if (tabBar) {
						tabBar.style.display = 'none';
					}
				},

				showTabBarInH5() {
					const tabBar = document.querySelector('.uni-tabbar');
					if (tabBar) {
						tabBar.style.display = 'flex';
					}
				},

				goBack() {
					this.showTabBar();
					uni.switchTab({
						url: '/pages/home/home'
					});
				},

				onInput(event) {
					this.inputMessage = event.detail.value;
				},

				onLineChange(event) {
					this.inputLineCount = event.detail.lineCount;
				},

				async sendMessage() {
					if (!this.canSend) return;

					const userMessage = this.inputMessage.trim();
					this.inputMessage = '';
					this.inputLineCount = 1;

					this.addMessage({
						role: 'user',
						message_type: 'text',
						content: userMessage,
						created_at: new Date().toISOString()
					});

					this.loading = true;
					this.isStreaming = true;
					this.streamingMessage = ''; // 清空流式内容

					try {
						const response = await uni.request({
							url: `${API_BASE_URL}/chat/consult`,
							method: 'POST',
							header: {
								'Authorization': `Bearer ${this.token}`,
								'Content-Type': 'application/json'
							},
							data: {
								question: userMessage,
								session_id: this.currentSessionId
							},
							timeout: 30000
						});

						if (response.statusCode === 200) {
							let aiResponse = '';
							const data = response.data;
							if (typeof data === 'string') {
								aiResponse = data;
							} else if (data.answer) {
								aiResponse = data.answer;
							} else if (data.content) {
								aiResponse = data.content;
							} else {
								aiResponse = '抱歉，没有收到回复';
							}

							// 添加一个占位的 assistant 消息（内容为空）
							const messageIndex = this.messages.length;
							this.addMessage({
								role: 'assistant',
								message_type: 'text',
								content: '',
								created_at: new Date().toISOString(),
								isStreaming: true // 标记为流式中
							});

							// 开始模拟流式输出
							await this.simulateTyping(aiResponse, messageIndex);

							// 流式结束后更新 session_id（如有）
							if (data.session_id && !this.currentSessionId) {
								this.currentSessionId = data.session_id;
							}
						} else {
							throw new Error(`请求失败: ${response.statusCode}`);
						}
					} catch (error) {
						console.error('发送消息失败:', error);
						this.addMessage({
							role: 'assistant',
							message_type: 'text',
							content: '抱歉，服务暂时不可用，请稍后重试',
							created_at: new Date().toISOString()
						});
					} finally {
						this.loading = false;
						this.isStreaming = false;
					}
				},

				async simulateTyping(fullText, messageIndex) {
					const delay = 20; // 每个字符间隔 ms，可调快慢
					for (let i = 0; i <= fullText.length; i++) {
						if (!this.isStreaming) break; // 可被中断
						this.$set(this.messages[messageIndex], 'content', fullText.substring(0, i));
						await this.sleep(delay);
					}
					// 移除流式标记
					this.$set(this.messages[messageIndex], 'isStreaming', false);
				},

				sleep(ms) {
					return new Promise(resolve => setTimeout(resolve, ms));
				},

				// 修改 uploadImage 方法中的处理逻辑
				async uploadImage() {
					try {
						const [error, res] = await new Promise(resolve => {
							uni.chooseImage({
								count: 1,
								sizeType: ['compressed'],
								sourceType: ['album', 'camera'],
								success: (res) => resolve([null, res]),
								fail: (err) => resolve([err, null])
							});
						});

						if (error) {
							throw error;
						}

						const tempFile = res.tempFiles[0];

						// 添加用户图片消息
						this.addMessage({
							role: 'user',
							message_type: 'image',
							content: '[图片消息]',
							image_url: tempFile.path,
							created_at: new Date().toISOString()
						});

						this.globalLoading = true;

						// 使用 uni.uploadFile 处理文件上传
						const [uploadError, uploadRes] = await new Promise(resolve => {
							uni.uploadFile({
								url: `${API_BASE_URL}/chat/upload-image`,
								filePath: tempFile.path,
								name: 'file',
								header: {
									'Authorization': `Bearer ${this.token}`
								},
								formData: {
									session_id: this.currentSessionId || ''
								},
								success: (res) => resolve([null, res]),
								fail: (err) => resolve([err, null])
							});
						});

						if (uploadError) {
							throw uploadError;
						}

						if (uploadRes.statusCode === 200) {
							// 处理流式响应文本
							const responseText = uploadRes.data;

							// 添加AI消息
							this.addMessage({
								role: 'assistant',
								message_type: 'text',
								content: responseText,
								created_at: new Date().toISOString()
							});

							// 修复：安全地获取响应头
							if (uploadRes.header && uploadRes.header['X-Session-ID']) {
								const responseSessionId = uploadRes.header['X-Session-ID'];
								if (responseSessionId && !this.currentSessionId) {
									this.currentSessionId = responseSessionId;
								}
							}

						} else {
							throw new Error(`上传失败: ${uploadRes.statusCode}`);
						}

					} catch (error) {
						console.error('上传图片失败:', error);

						// 只显示一次错误消息
						this.addMessage({
							role: 'assistant',
							message_type: 'text',
							content: '图片分析失败，请稍后重试',
							created_at: new Date().toISOString()
						});

						uni.showToast({
							title: '图片上传失败',
							icon: 'none'
						});
					} finally {
						this.globalLoading = false;
					}
				},

				previewImage(url) {
					uni.previewImage({
						urls: [url],
						current: 0
					});
				},

				async showHistory() {
					await this.loadSessions();
					this.showHistoryModal = true;
				},

				closeHistoryModal() {
					this.showHistoryModal = false;
				},

				async loadSessions() {
					try {
						const [error, response] = await new Promise(resolve => {
							uni.request({
								url: `${API_BASE_URL}/chat/sessions`,
								method: 'GET',
								header: {
									'Authorization': `Bearer ${this.token}`,
									'Content-Type': 'application/json'
								},
								success: (res) => resolve([null, res]),
								fail: (err) => resolve([err, null])
							});
						});

						if (error) throw error;

						if (response.statusCode === 200) {
							this.sessions = response.data.sessions || [];
						} else {
							throw new Error(response.data.detail || '加载失败');
						}
					} catch (error) {
						console.error('加载会话失败:', error);
						uni.showToast({
							title: '加载失败',
							icon: 'none'
						});
					}
				},

				async createNewSession() {
					try {
						const [error, response] = await new Promise(resolve => {
							uni.request({
								url: `${API_BASE_URL}/chat/sessions/new`,
								method: 'POST',
								header: {
									'Authorization': `Bearer ${this.token}`,
									'Content-Type': 'application/json'
								},
								success: (res) => resolve([null, res]),
								fail: (err) => resolve([err, null])
							});
						});

						if (error) throw error;

						if (response.statusCode === 200) {
							this.currentSessionId = response.data.session_id;
							this.messages = [];
							await this.loadSessionMessages(this.currentSessionId);
						} else {
							throw new Error(response.data.detail || '创建失败');
						}
					} catch (error) {
						console.error('创建会话失败:', error);
						this.currentSessionId = this.generateSessionId();
						this.messages = [];
					}
				},

				async selectSession(sessionId) {
					this.currentSessionId = sessionId;
					this.showHistoryModal = false;
					await this.loadSessionMessages(sessionId);
				},

				async loadSessionMessages(sessionId) {
					try {
						const [error, response] = await new Promise(resolve => {
							uni.request({
								url: `${API_BASE_URL}/chat/sessions/${sessionId}/messages`,
								method: 'GET',
								header: {
									'Authorization': `Bearer ${this.token}`,
									'Content-Type': 'application/json'
								},
								success: (res) => resolve([null, res]),
								fail: (err) => resolve([err, null])
							});
						});

						if (error) throw error;

						if (response.statusCode === 200) {
							this.messages = response.data.messages || [];
						} else {
							throw new Error(response.data.detail || '加载消息失败');
						}
					} catch (error) {
						console.error('加载消息失败:', error);
						this.messages = [];
					}
				},

				async deleteSession(sessionId) {
					this.showHistoryModal = false;

					await new Promise(resolve => setTimeout(resolve, 100));

					uni.showModal({
						title: '确认删除',
						content: '确定要删除这个会话吗？',
						confirmColor: '#FF4444',
						success: async (res) => {
							if (res.confirm) {
								try {
									const [error, response] = await new Promise(resolve => {
										uni.request({
											url: `${API_BASE_URL}/chat/history/${sessionId}`,
											method: 'DELETE',
											header: {
												'Authorization': `Bearer ${this.token}`,
												'Content-Type': 'application/json'
											},
											success: (res) => resolve([null, res]),
											fail: (err) => resolve([err, null])
										});
									});

									if (error) throw error;

									if (response.statusCode === 200) {
										uni.showToast({
											title: '删除成功',
											icon: 'success'
										});
										await this.loadSessions();
										if (sessionId === this.currentSessionId) {
											await this.createNewSession();
										}
									} else {
										throw new Error(response.data.detail || '删除失败');
									}
								} catch (error) {
									console.error('删除会话失败:', error);
									uni.showToast({
										title: '删除失败',
										icon: 'none'
									});
								}
							} else {
								this.showHistoryModal = true;
							}
						}
					});
				},

				async clearAllSessions() {
					uni.showModal({
						title: '确认清空',
						content: '确定要清空所有聊天记录吗？此操作不可恢复',
						confirmColor: '#FF4444',
						success: async (res) => {
							if (res.confirm) {
								try {
									const [error, response] = await new Promise(resolve => {
										uni.request({
											url: `${API_BASE_URL}/chat/history`,
											method: 'DELETE',
											header: {
												'Authorization': `Bearer ${this.token}`,
												'Content-Type': 'application/json'
											},
											success: (res) => resolve([null, res]),
											fail: (err) => resolve([err, null])
										});
									});

									if (error) throw error;

									if (response.statusCode === 200) {
										uni.showToast({
											title: '清空成功',
											icon: 'success'
										});
										this.showHistoryModal = false;
										await this.createNewSession();
										await this.loadSessions();
									} else {
										throw new Error(response.data.detail || '清空失败');
									}
								} catch (error) {
									console.error('清空会话失败:', error);
									uni.showToast({
										title: '清空失败',
										icon: 'none'
									});
								}
							}
						}
					});
				},

				addMessage(message) {
					this.messages.push(message);
				},

				updateLastMessage(content) {
					if (this.messages.length > 0) {
						const lastMessage = this.messages[this.messages.length - 1];
						if (lastMessage.role === 'assistant') {
							lastMessage.content = content;
							this.messages = [...this.messages];
						}
					}
				},

				scrollToBottom() {
					this.$nextTick(() => {
						this.scrollTop = 999999;
					});
				},

				onScroll(event) {
					// 可以在这里实现滚动加载更多消息
				},

				generateSessionId() {
					return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
				},

				formatTime(timeString) {
					if (!timeString) return '';
					try {
						const date = new Date(timeString);
						const now = new Date();
						const diff = now - date;
						const minutes = Math.floor(diff / (1000 * 60));

						if (minutes < 1) return '刚刚';
						if (minutes < 60) return `${minutes}分钟前`;

						return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
					} catch (e) {
						return timeString;
					}
				},

				formatSessionTime(timeString) {
					if (!timeString) return '';
					try {
						const date = new Date(timeString);
						const now = new Date();
						const diff = now - date;
						const days = Math.floor(diff / (1000 * 60 * 60 * 24));

						if (days === 0) {
							return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
						} else if (days === 1) {
							return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
						} else {
							return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
						}
					} catch (e) {
						return timeString;
					}
				}
			}
		};
	</script>

	<style scoped>
		.chat-page {
			position: relative;
			height: 100vh;
			background: linear-gradient(180deg, #f9f7ff 0%, #f0ebff 100%);
			display: flex;
			flex-direction: column;
		}

		.top-bg {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 300rpx;
			background: linear-gradient(135deg, #8A2BE2 0%, #9370DB 50%, #DA70D6 100%);
			z-index: 0;
			overflow: hidden;
		}

		.bg-shape {
			position: absolute;
			border-radius: 50%;
			background: rgba(255, 255, 255, 0.1);
		}

		.bg-shape-1 {
			width: 200rpx;
			height: 200rpx;
			top: -100rpx;
			right: -50rpx;
		}

		.bg-shape-2 {
			width: 150rpx;
			height: 150rpx;
			bottom: 30rpx;
			left: -60rpx;
		}

		.bg-shape-3 {
			width: 100rpx;
			height: 100rpx;
			top: 80rpx;
			left: 25%;
		}

		/* 头部导航 */
		.chat-header {
			position: relative;
			z-index: 10;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 80rpx 30rpx 30rpx;
			background: transparent;
		}

		.header-left {
			display: flex;
			align-items: center;
			gap: 20rpx;
		}

		.back-btn {
			width: 60rpx;
			height: 60rpx;
			border-radius: 50%;
			background: rgba(255, 255, 255, 0.9);
			display: flex;
			align-items: center;
			justify-content: center;
			box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
			backdrop-filter: blur(10px);
		}

		.back-icon {
			width: 32rpx;
			height: 32rpx;
		}

		.header-title {
			font-size: 36rpx;
			font-weight: 700;
			color: white;
		}

		.header-right {
			display: flex;
			gap: 20rpx;
		}

		.icon-btn {
			width: 60rpx;
			height: 60rpx;
			border-radius: 50%;
			background: rgba(255, 255, 255, 0.9);
			display: flex;
			align-items: center;
			justify-content: center;
			box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
			backdrop-filter: blur(10px);
		}

		.history-icon,
		.new-session-icon {
			width: 32rpx;
			height: 32rpx;
		}

		/* 聊天内容区域 */
		.chat-content {
			flex: 1;
			padding: 20rpx 30rpx;
			position: relative;
			z-index: 1;
			background: transparent;
		}

		.welcome-section {
			text-align: center;
			padding: 120rpx 0;
		}

		.welcome-icon {
			font-size: 80rpx;
			margin-bottom: 20rpx;
		}

		.welcome-title {
			font-size: 36rpx;
			font-weight: 700;
			color: #333;
			display: block;
			margin-bottom: 16rpx;
		}

		.welcome-desc {
			font-size: 28rpx;
			color: #666;
			line-height: 1.5;
		}

		/* 消息样式 */
		.messages-container {
			padding-bottom: 20rpx;
		}

		.message-item {
			margin-bottom: 40rpx;
		}

		.message-ai,
		.message-user {
			display: flex;
			align-items: flex-start;
			gap: 20rpx;
		}

		.message-user {
			justify-content: flex-end;
			padding-right: 60rpx;
		}

		.avatar {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 24rpx;
			font-weight: 600;
			color: white;
			flex-shrink: 0;
			overflow: hidden;
		}

		.ai-avatar {
			background: linear-gradient(135deg, #8A2BE2 0%, #9370DB 100%);
		}

		.user-avatar {
			background: linear-gradient(135deg, #FF6B6B 0%, #FFA500 100%);
		}

		.avatar-image {
			width: 100%;
			height: 100%;
			border-radius: 50%;
		}

		.message-content {
			max-width: 500rpx;
			display: flex;
			flex-direction: column;
			gap: 12rpx;
		}

		.message-ai .message-content {
			align-items: flex-start;
		}

		.message-user .message-content {
			align-items: flex-end;
		}

		.message-text {
			padding: 24rpx 32rpx;
			border-radius: 32rpx;
			font-size: 28rpx;
			line-height: 1.5;
			word-wrap: break-word;
		}

		.message-ai .message-text {
			background: white;
			color: #333;
			border-bottom-left-radius: 8rpx;
			box-shadow: 0 4rpx 20rpx rgba(138, 43, 226, 0.1);
		}

		.message-user .message-text {
			background: linear-gradient(135deg, #8A2BE2 0%, #9370DB 100%);
			color: white;
			border-bottom-right-radius: 8rpx;
			box-shadow: 0 4rpx 20rpx rgba(138, 43, 226, 0.2);
		}

		.image-message {
			border-radius: 24rpx;
			overflow: hidden;
			box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
		}

		.uploaded-image {
			width: 300rpx;
			height: 300rpx;
			border-radius: 24rpx;
		}

		.message-time {
			font-size: 22rpx;
			color: #999;
		}

		/* 加载状态 */
		.loading-message {
			display: flex;
			align-items: flex-start;
			gap: 20rpx;
			margin-bottom: 40rpx;
		}

		.typing-indicator {
			display: flex;
			align-items: center;
			gap: 8rpx;
			padding: 24rpx 32rpx;
			background: white;
			border-radius: 32rpx;
			border-bottom-left-radius: 8rpx;
			box-shadow: 0 4rpx 20rpx rgba(138, 43, 226, 0.1);
		}

		.typing-dot {
			width: 12rpx;
			height: 12rpx;
			border-radius: 50%;
			background: #8A2BE2;
			animation: typing 1.4s infinite ease-in-out;
		}

		.typing-dot:nth-child(1) {
			animation-delay: -0.32s;
		}

		.typing-dot:nth-child(2) {
			animation-delay: -0.16s;
		}

		@keyframes typing {

			0%,
			80%,
			100% {
				transform: scale(0.8);
				opacity: 0.5;
			}

			40% {
				transform: scale(1);
				opacity: 1;
			}
		}

		/* 底部输入区域 */
		.input-section-fixed {
			position: fixed;
			left: 0;
			width: 100%;
			background: white;
			padding: 20rpx, 30rpx;
			box-shadow: 0 -4rpx 30rpx rgba(0, 0, 0, 0.1);
			z-index: 100;
		}

		.input-container {
			display: flex;
			align-items: flex-start;
			/* 改为 flex-start，使内容从顶部开始 */
			gap: 20rpx;
			background: #f8f9fa;
			border-radius: 40rpx;
			padding: 20rpx 24rpx;
			border: 2rpx solid #e9ecef;
			transition: all 0.3s ease;
		}

		.input-container:focus-within {
			border-color: #8A2BE2;
			background: white;
			box-shadow: 0 4rpx 20rpx rgba(138, 43, 226, 0.1);
		}

		.input-scroll {
			flex: 1;
			max-height: 160rpx;
		}

		.chat-input {
			width: 100%;
			font-size: 28rpx;
			line-height: 1.4;
			padding: 0;
			/* 关键：去掉默认上下 padding */
			background: transparent;
			border: none;
			outline: none;
			min-height: 40rpx;
			max-height: 160rpx;
			box-sizing: border-box;
			vertical-align: top;
			resize: none;
			/* 禁止用户手动拉伸 */
		}

		.chat-input::placeholder {
			color: #999;
		}

		.input-actions {
			display: flex;
			align-items: center;
			gap: 16rpx;
		}

		.upload-btn {
			width: 60rpx;
			height: 60rpx;
			border-radius: 50%;
			background: white;
			display: flex;
			align-items: center;
			justify-content: center;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
		}

		.upload-icon {
			width: 32rpx;
			height: 32rpx;
		}

		.send-btn {
			background: linear-gradient(135deg, #8A2BE2 0%, #9370DB 100%);
			color: white;
			border: none;
			border-radius: 30rpx;
			padding: 16rpx 32rpx;
			font-size: 28rpx;
			font-weight: 600;
			transition: all 0.3s ease;
			box-shadow: 0 4rpx 20rpx rgba(138, 43, 226, 0.3);
		}

		.send-btn:disabled {
			background: #ccc;
			box-shadow: none;
			transform: none;
		}

		.send-btn:active:not(:disabled) {
			transform: scale(0.95);
		}

		.send-text {
			color: white;
		}

		/* 模态框样式 */
		.modal-mask {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background: rgba(0, 0, 0, 0.5);
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 1000;
			padding: 40rpx;
		}

		.modal-content {
			background: white;
			border-radius: 24rpx;
			width: 100%;
			max-width: 600rpx;
			max-height: 80vh;
			overflow: hidden;
			box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.2);
			animation: modalSlideIn 0.3s ease;
		}

		@keyframes modalSlideIn {
			from {
				opacity: 0;
				transform: translateY(100rpx);
			}

			to {
				opacity: 1;
				transform: translateY(0);
			}
		}

		.modal-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 40rpx 32rpx 20rpx;
			border-bottom: 2rpx solid #f0f0f0;
		}

		.modal-title {
			font-size: 32rpx;
			font-weight: 700;
			color: #333;
		}

		.modal-close {
			font-size: 40rpx;
			color: #999;
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 50%;
		}

		.modal-close:active {
			background: #f5f5f5;
		}

		.modal-body {
			padding: 0;
			max-height: 60vh;
		}

		.sessions-list {
			max-height: 500rpx;
			padding: 20rpx 0;
		}

		.empty-sessions {
			text-align: center;
			padding: 80rpx 0;
			color: #999;
		}

		.empty-text {
			font-size: 28rpx;
		}

		.session-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 24rpx 32rpx;
			border-bottom: 1rpx solid #f5f5f5;
			transition: background 0.3s ease;
		}

		.session-item:active {
			background: #f8f9fa;
		}

		.session-info {
			flex: 1;
			display: flex;
			flex-direction: column;
			gap: 8rpx;
		}

		.session-time {
			font-size: 28rpx;
			color: #333;
			font-weight: 600;
		}

		.session-count {
			font-size: 24rpx;
			color: #999;
		}

		.session-actions {
			margin-left: 20rpx;
		}

		.delete-btn {
			background: #ff4757;
			color: white;
			border: none;
			border-radius: 20rpx;
			padding: 12rpx 24rpx;
			font-size: 24rpx;
		}

		.delete-btn:active {
			background: #ff3742;
			transform: scale(0.95);
		}

		.modal-footer {
			padding: 24rpx 32rpx;
			border-top: 2rpx solid #f0f0f0;
		}

		.modal-button {
			width: 100%;
			background: linear-gradient(135deg, #8A2BE2 0%, #9370DB 100%);
			color: white;
			border: none;
			border-radius: 24rpx;
			padding: 24rpx;
			font-size: 28rpx;
			font-weight: 600;
		}

		.modal-button:active {
			transform: scale(0.98);
		}

		/* 加载遮罩 */
		.loading-mask {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background: rgba(0, 0, 0, 0.5);
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			z-index: 2000;
		}

		.loading-spinner {
			width: 80rpx;
			height: 80rpx;
			border: 6rpx solid rgba(255, 255, 255, 0.3);
			border-top: 6rpx solid white;
			border-radius: 50%;
			animation: spin 1s linear infinite;
			margin-bottom: 20rpx;
		}

		@keyframes spin {
			0% {
				transform: rotate(0deg);
			}

			100% {
				transform: rotate(360deg);
			}
		}

		.loading-text {
			color: white;
			font-size: 28rpx;
		}

		/* 底部安全区域 */
		.bottom-space {
			height: 40rpx;
		}

		/* 响应式设计 */
		@media (max-width: 750rpx) {
			.chat-header {
				padding: 60rpx 20rpx 20rpx;
			}

			.chat-content {
				padding: 20rpx;
			}

			/* 
			.input-section-fixed {
				padding: 20rpx;
			} */

			.message-content {
				max-width: 450rpx;
			}

			.modal-mask {
				padding: 20rpx;
			}
		}

		/* 深色模式支持 */
		@media (prefers-color-scheme: dark) {
			.chat-page {
				background: linear-gradient(180deg, #1a1a1a 0%, #2d2d2d 100%);
			}

			.welcome-title {
				color: white;
			}

			.welcome-desc {
				color: #ccc;
			}

			.input-container {
				background: #2d2d2d;
				border-color: #404040;
			}

			.chat-input {
				color: white;
			}

			.modal-content {
				background: #2d2d2d;
			}

			.modal-title {
				color: white;
			}

			.session-time {
				color: white;
			}

			.session-item:active {
				background: #3d3d3d;
			}
		}
	</style>